package com.haina.shop.controller.tzuser;
import com.haina.shop.constant.JwtClaimsConstant;
import com.haina.shop.domain.User;
import com.haina.shop.dto.LoginDTO;
import com.haina.shop.properties.JwtProperties;
import com.haina.shop.result.ServiceResult;
import com.haina.shop.service.UserService;
import com.haina.shop.utils.JwtUtil;
import com.haina.shop.vo.LoginVO;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping()
public class LoginController {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtProperties jwtProperties;
    /**
     * 小程序用户登录
     *
     * @param dto
     * @return
     */
    @PostMapping("/login")
    public ServiceResult login(@RequestBody LoginDTO dto) {
        ServiceResult login=userService.login(dto);
        if(login.isSuccess()){
            //成功获取用户的数据
           User user=(User)login.getData();
            //登录成功后，生成jwt令牌
            Map<String, Object> claims = new HashMap<>();
            claims.put(JwtClaimsConstant.user_ID, user.getUserId());
            String token = JwtUtil.createJWT(
                    jwtProperties.getUserSecretKey(),
                    jwtProperties.getUserTtl(),
                    claims);
            //创建登录成功返回的实体
            LoginVO loginVO = new LoginVO(token, token, jwtProperties.getUserTtl());
            return ServiceResult.LoginSuccess(loginVO);
        }else{
            return login;
        }
    }

    /**
     * 用户退出登录
     * @return
     */
    @PostMapping("/logOut")
    public ServiceResult logout(){
        return ServiceResult.success();
    }

    @PostMapping("/add")
    public String add(@RequestBody LoginDTO dto){
        User user = new User();
        user.setRealName(dto.getUserName());
        user.setUserMail(dto.getUserName());
        //加盐哈希密码
        String LoginPassword= BCrypt.hashpw("123456",BCrypt.gensalt());
        user.setLoginPassword(LoginPassword);
        user.setUserMobile(dto.getMobile());
        user.setModifyTime(new Date());
        user.setUserRegtime(new Date());
        user.setSex("男");
        user.setPic("https://img2.baidu.com/it/u=2239350219,2012909916&fm=253&fmt=auto&app=138&f=JPEG?w=800&h=1066");
        user.setStatus(1);
        boolean save = userService.save(user);
        if(save){
            return "ok";
        }else return "fail";
    }
}
